import React, { useEffect, useState, useRef } from 'react';
import { Form, Input, Button, ImageUploader, TextArea, SpinLoading } from 'antd-mobile';
import styles from './index.module.less';
import HeaderNav from "@/components/header-nav";
import { useSearchParams } from 'react-router-dom';
const { createWorldRole, getUserWorldBookDetails, editRole } = $globalServicer('world')
import { handleImageUpload } from '@/utils/upload';
import { defaultRoleCover } from '@/utils/config';
import { showErrorToast, showSuccessToast } from '@/utils/customToast';
const premiumCard = () => {
  const [roleForm] = Form.useForm();
  const [params] = useSearchParams();
  const id = params.get('id');
  const type = params.get('type');
  const customNavigate = $globalNavigate()
  const [submitting, setSubmitting] = useState(false)
  const [activeTab, setActiveTab] = useState('ai-settings')
  const [isInitialized, setIsInitialized] = useState(false)
  const [forceUpdate, setForceUpdate] = useState(0)
  const [initialValues, setInitialValues] = useState({})
  const [loading, setLoading] = useState(false)
  const [fontsLoaded, setFontsLoaded] = useState(false)

  // 检测字体加载状态
  useEffect(() => {
    const checkFontsLoaded = async () => {
      try {
        // 检测Material Icons字体是否加载完成
        if (document.fonts && document.fonts.ready) {
          await document.fonts.ready;
          // 给container添加fonts-loaded类
          document.body.classList.add('fonts-loaded');
          setFontsLoaded(true);
        } else {
          // 如果不支持Font Loading API，使用延迟显示
          setTimeout(() => {
            document.body.classList.add('fonts-loaded');
            setFontsLoaded(true);
          }, 300);
        }
      } catch (error) {
        console.warn('Font loading detection failed, using fallback:', error);
        // 出错时也显示，避免一直不显示
        setTimeout(() => {
          document.body.classList.add('fonts-loaded');
          setFontsLoaded(true);
        }, 300);
      }
    };

    checkFontsLoaded();

    // 清理函数
    return () => {
      // 组件卸载时不移除fonts-loaded类，因为字体已经加载，其他页面可以继续使用
    };
  }, []);

  useEffect(() => {
    if (id && !isInitialized) {
      setLoading(true);
      getUserWorldBookDetails(id).then(res => {
        
        let result = {
          ...res,
          advanced_description: res.description?.advanced_description || res.advanced_description || '',
          cover: res.cover ? [
            {
              url: res.cover
            }
          ] : [],
          // 用户设定字段 - 由于接口暂时没有 role 相关数据，先使用默认值
          role_cover: [],
          persona_name: '',
          remarks: ''
        }
        // 从 description 对象中获取用户设定数据
        if (res.description) {
          if (res.description.role_cover) {
            result.role_cover = [
              {
                url: res.description.role_cover
              }
            ];
          }
          if (res.description.persona_name) {
            result.persona_name = res.description.persona_name;
          }
          if (res.description.remarks) {
            result.remarks = res.description.remarks;
          }
        }
        // 如果 description 中不存在，尝试从根级别获取（兼容旧数据）
        else {
          if (res.role_cover) {
            result.role_cover = [{ url: res.role_cover }];
          }
          if (res.persona_name) {
            result.persona_name = res.persona_name;
          }
          if (res.remarks) {
            result.remarks = res.remarks;
          }
        }
        
        
        // 设置表单值
        console.log('📝 设置表单数据:', result);
        setInitialValues(result);
        setIsInitialized(true);
        
        // 延迟设置表单值，确保Form组件已经渲染
        setTimeout(() => {
          try {
            roleForm.setFieldsValue(result);
            console.log('✅ 表单值设置成功:', result);
          } catch (error) {
            console.warn('Form not ready yet, retrying...', error);
            // 如果Form还没准备好，再次延迟重试
            setTimeout(() => {
              try {
                roleForm.setFieldsValue(result);
                console.log('✅ 表单值设置成功(重试):', result);
              } catch (retryError) {
                console.error('Failed to set form values:', retryError);
              }
            }, 200);
          }
        }, 100);
        
        // 强制重新渲染以确保显示数据
        setForceUpdate(prev => prev + 1);
        setLoading(false);
      }).catch(error => {
        console.error('❌ 获取数据失败:', error);
        setLoading(false);
      });
    }
    // 创建模式下不设置任何初始值，让用户自己填写
  }, [id, isInitialized])


  // 验证图片是否已上传
  const isImageUploaded = (imageField) => {
    if (!imageField || !Array.isArray(imageField) || imageField.length === 0) {
      return false;
    }
    const image = imageField[0];
    
    // 检查是否有有效的URL或path
    const hasUrl = !!(image.url || image.path);
    return hasUrl;
  };

  // 验证AI设定页面的必填项
  const validateAISettings = (values) => {
    const errors = [];
    
    if (!isImageUploaded(values.cover)) {
      errors.push('图片上传失败，请调整图片大小');
    }
    if (!values.name || values.name.trim() === '') {
      errors.push('智能体名称不能为空');
    }
    if (!values.advanced_description || values.advanced_description.trim() === '') {
      errors.push('智能体描述不能为空');
    }
    if (!values.first_message || values.first_message.trim() === '') {
      errors.push('故事第一句话不能为空');
    }
    
    return errors;
  };

  // 验证用户设定页面的必填项
  const validateUserSettings = (values) => {
    const errors = [];
    
    if (!isImageUploaded(values.role_cover)) {
      errors.push('图片上传失败，请调整图片大小');
    }
    if (!values.persona_name || values.persona_name.trim() === '') {
      errors.push('角色名称不能为空');
    }
    if (!values.remarks || values.remarks.trim() === '') {
      errors.push('角色描述不能为空');
    }
    
    return errors;
  };

  // 检查所有tab的必填项并自动切换到有未填写项的tab
  const validateAllTabs = (values) => {
    const aiSettingsErrors = validateAISettings(values);
    const userSettingsErrors = validateUserSettings(values);
    
    // 情况1: 当前是AI设定页面
    if (activeTab === 'ai-settings') {
      // 如果AI设定页面有未填项，不切换，让表单验证显示错误
      if (aiSettingsErrors.length > 0) {
        return false;
      }
      // 如果AI设定页面填写完了，但用户设定有未填项，切换到用户设定页面
      else if (userSettingsErrors.length > 0) {
        setActiveTab('user-settings');
        return false;
      }
    }
    
    // 情况2: 当前是用户设定页面
    if (activeTab === 'user-settings') {
      // 如果用户设定页面有未填项，不切换，让表单验证显示错误
      if (userSettingsErrors.length > 0) {
        return false;
      }
      // 如果用户设定页面填写完了，但AI设定有未填项，切换到AI设定页面
      else if (aiSettingsErrors.length > 0) {
        setActiveTab('ai-settings');
        return false;
      }
    }
    
    return true;
  };


  const onFinish = (values) => {
    if (submitting) return; // 如果正在提交，直接返回
    
    // 先触发表单验证，显示红色错误提示
    roleForm.validateFields().catch(() => {
      // 验证失败，不执行后续逻辑
    });
    
    // 验证所有tab的必填项并自动切换到有未填写项的tab
    if (!validateAllTabs(values)) {
      return; // 如果有未填写的必填项，停止提交
    }
    
    let submitData = {
      name: values.name,
      cover: values.cover[0].url || values.cover[0].path,
      description: {
        advanced_description: values.advanced_description,
        // 用户设定数据移到description对象中
        role_cover: values.role_cover[0].url || values.role_cover[0].path,
        persona_name: values.persona_name,
        remarks: values.remarks
      },
      first_message: values.first_message,
      type: 3
    }
    // 如果是编辑模式，添加id
    if (id && type === 'edit') {
      submitData.id = id
    }

    try {
      setSubmitting(true);
      if (id && type === 'edit') {
        editRole(submitData).then(res => {
          showSuccessToast('编辑成功！');
          setTimeout(() => {
            customNavigate(`/world`)
          }, 2000);
        }).catch(error => {
          showErrorToast('编辑失败，请重试');
        }).finally(() => {
          setSubmitting(false);
        });
      } else {
        createWorldRole(submitData).then(res => {
          showSuccessToast('创建成功！');
          setTimeout(() => {
            customNavigate(`/world`)
          }, 2000);
        }).catch(error => {
          showErrorToast('创建失败，请重试');
        }).finally(() => {
          setSubmitting(false);
        });
      }
    } catch (error) {
      showErrorToast('操作失败，请重试');
      setSubmitting(false);
    }
  };

  const [isRequired, setIsRequired] = useState(true)


  return (
    <div className={`${styles.container} dark-theme`}>
      <div className={styles.header}>
        <HeaderNav backArrow={true} title={`${id && type === 'edit' ? "编辑" : "创建"}智能体`}></HeaderNav>
      </div>

      <div className={styles.content}>
        <div className={styles.titleSection}>
          <h1 className={styles.mainTitle}>{id && type === 'edit' ? '编辑智能体' : '创建智能体'}</h1>
          <p className={styles.subtitle}>{id && type === 'edit' ? '修改设定，保存后返回智能体库' : '赋予生命，开启无限可能'}</p>
          
        </div>

        <div className={styles.tabContainer}>
          <button
            className={`${styles.tabButton} ${activeTab === 'ai-settings' ? styles.active : ''}`}
            onClick={() => setActiveTab('ai-settings')}
          >
            AI 设定
          </button>
          <button
            className={`${styles.tabButton} ${activeTab === 'user-settings' ? styles.active : ''}`}
            onClick={() => setActiveTab('user-settings')}
          >
            用户设定
          </button>
        </div>

        {loading ? (
          <div className={styles.loadingContainer}>
            <div className={styles.loadingBox}>
              <SpinLoading color='primary' />
              <p className={styles.loadingText}>正在加载数据...</p>
            </div>
          </div>
        ) : (
          <Form
            form={roleForm}
            onFinish={onFinish}
            className={styles.form}
            preserve={true}
            initialValues={initialValues}
            key={forceUpdate}
          >
          <div className={styles.tabContent} style={{ display: activeTab === 'ai-settings' ? 'block' : 'none' }}>
            <div className={styles.glassCard}>
              <div className={styles.cardHeader}>
                <div className={styles.iconWrapper}>
                  <span className="material-icons-outlined">auto_awesome</span>
                </div>
                <div className={styles.headerText}>
                  <h2 className={styles.cardTitle}>基础信息</h2>
                  <p className={styles.cardSubtitle}>定义它的核心身份</p>
                </div>
              </div>

              <div className={styles.avatarSection}>
                <Form.Item name="cover" required={isRequired} rules={[{ required: isRequired, message: '图片上传失败，请调整图片大小' }]}>
                  <div>
                    <div className={styles.avatarUpload}>
                      <ImageUploader
                          style={{'--cell-size': '120px'}}
                          className={styles.uploadWrapper}
                          upload={handleImageUpload}
                          maxCount={1}
                          defaultValue={initialValues.cover || []}
                          onChange={(fileList) => {
                            try {
                              roleForm.setFieldValue('cover', fileList);
                              // 清除验证错误提示
                              roleForm.setFields([{
                                name: 'cover',
                                errors: []
                              }]);
                            } catch (error) {
                              console.warn('Form not ready for cover update:', error);
                            }
                          }}
                          onDelete={() => {
                            return {beforeDelete: () => true};
                          }}
                      >
                        <span className="material-icons-outlined add-a-photo-icon">add_a_photo</span>
                      </ImageUploader>
                    </div>
                    <p className={styles.uploadText}>上传头像(仅支持2MB大小以下图片上传)</p>
                  </div>
                </Form.Item>
              </div>

              <div className={styles.formFields}>
                <Form.Item name="name" required={isRequired} rules={[{ required: isRequired, message: '智能体名称不能为空' }]}>
                  <div className={styles.fieldGroup}>
                    <label className={styles.label}>
                      <span className="material-icons-outlined mr-10">badge</span>
                      智能体名称
                    </label>
                    <Input
                      className={styles.formInput}
                      placeholder="给你的智能体命名"
                      maxLength={20}
                      defaultValue={initialValues.name || ''}
                    />
                  </div>
                </Form.Item>

                <Form.Item name="advanced_description" required={isRequired} rules={[{ required: isRequired, message: '智能体描述不能为空' }]}>
                  <div className={styles.fieldGroup}>
                    <label className={styles.label}>
                      <span className="material-icons-outlined mr-10">description</span>
                      智能体描述
                    </label>
                    <TextArea
                      className={styles.formInput}
                      placeholder="此处填写内容为智能体的专属设定，其他用户不可见。包括但不限于单独人物的设定，如人物性格、外貌、身份、背景、说话风格、与用户（主控）的关系等内容"
                      rows={4}
                      maxLength={8000}
                      defaultValue={initialValues.advanced_description || ''}
                    />
                  </div>
                </Form.Item>
              </div>
            </div>

            <div className={styles.glassCard}>
              <div className={styles.cardHeader}>
                <div className={styles.iconWrapper}>
                  <span className="material-icons-outlined">auto_stories</span>
                </div>
                <div className={styles.headerText}>
                  <h2 className={styles.cardTitle}>故事开篇</h2>
                  <p className={styles.cardSubtitle}>为你的冒险写下第一行代码</p>
                </div>
              </div>

              <div className={styles.formFields}>
                <Form.Item name="first_message" required={isRequired} rules={[{ required: isRequired, message: '故事第一句话不能为空' }]}>
                  <div className={styles.fieldGroup}>
                    <label className={styles.label}>
                      <span className="material-icons-outlined mr-10">play_circle_outline</span>
                      故事第一句话
                    </label>
                    <TextArea
                      className={styles.formInput}
                      placeholder="是该智能体设定下，故事的开篇"
                      rows={4}
                      maxLength={1500}
                      defaultValue={initialValues.first_message || ''}
                    />
                  </div>
                </Form.Item>
              </div>
            </div>
          </div>

          <div className={styles.tabContent} style={{ display: activeTab === 'user-settings' ? 'block' : 'none' }}>
            <div className={styles.glassCard}>
              <div className={styles.cardHeader}>
                <div className={styles.iconUser}>
                  <span className="material-icons-outlined">account_circle</span>
                </div>
                <div className={styles.headerText}>
                  <h2 className={styles.cardTitle}>你的角色</h2>
                  <p className={styles.cardSubtitle}>定义你在故事中的身份</p>
                </div>
              </div>

              <div className={styles.avatarSection}>
                <Form.Item name="role_cover" required={isRequired} rules={[{ required: isRequired, message: '图片上传失败，请调整图片大小' }]}>
                  <div>
                    <div className={styles.avatarUpload}>
                      <ImageUploader
                          style={{'--cell-size': '120px'}}
                          className={styles.uploadWrapper}
                          upload={handleImageUpload}
                          maxCount={1}
                          defaultValue={initialValues.role_cover || []}
                          onChange={(fileList) => {
                            try {
                              roleForm.setFieldValue('role_cover', fileList);
                              // 清除验证错误提示
                              roleForm.setFields([{
                                name: 'role_cover',
                                errors: []
                              }]);
                            } catch (error) {
                              console.warn('Form not ready for role_cover update:', error);
                            }
                          }}
                          onDelete={() => {
                            return {beforeDelete: () => true};
                          }}
                      >
                        <span className="material-icons-outlined add-a-photo-icon">add_a_photo</span>
                      </ImageUploader>
                    </div>
                    <p className={styles.uploadText}>上传头像(仅支持2MB大小以下图片上传)</p>
                  </div>
                </Form.Item>
              </div>

              <div className={styles.formFields}>
                <Form.Item name="persona_name" required={isRequired} rules={[{ required: isRequired, message: '角色名称不能为空' }]}>
                  <div className={styles.fieldGroup}>
                    <label className={styles.label}>
                      <span className="material-icons-outlined mr-10">face</span>
                      你的角色名称
                    </label>
                    <Input
                      className={styles.formInput}
                      placeholder="给你自己所扮演的角色起名"
                      maxLength={20}
                      defaultValue={initialValues.persona_name || ''}
                    />
                  </div>
                </Form.Item>

                <Form.Item name="remarks" required={isRequired} rules={[{ required: isRequired, message: '角色描述不能为空' }]}>
                  <div className={styles.fieldGroup}>
                    <label className={styles.label}>
                      <span className="material-icons-outlined mr-10">person_search</span>
                      你的角色描述
                    </label>
                    <TextArea
                      className={styles.formInput}
                      placeholder="此处填写内容为你所扮演角色的专属设定，包括但不限于你的人物的设定，如人物性格、外貌、身份、背景、说话风格、与智能体的关系等内容"
                      rows={4}
                      maxLength={1000}
                      defaultValue={initialValues.remarks || ''}
                    />
                  </div>
                </Form.Item>
              </div>
            </div>
          </div>

          <div className={styles.submitSection}>
            <Button
              className={styles.submitButton}
              type='button'
              loading={submitting}
              disabled={submitting}
              onClick={() => {
                const values = roleForm.getFieldsValue();
                onFinish(values);
              }}
            >
              <span className="material-icons-outlined">rocket_launch</span>
              <span>{submitting ? '提交中...' : (id && type === 'edit' ? '编辑完成，返回智能体库' : '完成创建，返回智能体库')}</span>
            </Button>
          </div>
        </Form>
        )}
      </div>
    </div>
  );
};

export default premiumCard;